package com.rlz.framemm.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by RLZ
 * on 2021/10/15
 */
public class TestRetrofit {

    private ProxyBookAdapterFactory mProxyBookAdapterFactory;

    public TestRetrofit(ProxyBookAdapterFactory proxyBookAdapterFactory) {
        mProxyBookAdapterFactory = proxyBookAdapterFactory;
    }

    @SuppressWarnings("unchecked")
    public <T> T create(final Class<T> clazz) {
        return (T) Proxy.newProxyInstance(
                clazz.getClassLoader(),
                new Class<?>[]{clazz},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws
                            InvocationTargetException, IllegalAccessException {
                        if (method.getDeclaringClass() == Object.class)
                            return method.invoke(this, args);
                        return new JavaBook();
                    }
                }
        );
    }

    public static final class Builder {
        private ProxyBookAdapterFactory mProxyBookAdapterFactory;

        public Builder setProxyBookAdapterFactory(ProxyBookAdapterFactory proxyBookAdapterFactory) {
            mProxyBookAdapterFactory = proxyBookAdapterFactory;
            return this;
        }

        public TestRetrofit build() {
            return new TestRetrofit(mProxyBookAdapterFactory);
        }
    }
}
